package com.max.blepro.ui;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothProfile;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.max.blepro.R;
import com.max.blepro.base.StatusNavigationActivity;
import com.max.blepro.service.BluetoothLeService;
import com.max.blepro.util.ChangeTool;
import com.max.blepro.util.LogUtil;
import com.max.blepro.util.UpdateCommand;

public class BleConnectDeviceActivity extends StatusNavigationActivity {

    private final static String TAG = "BleConnectDeviceActivity";
    public static String EXTRAS_DEVICE_NAME = "DEVICE_NAME";;
    public static String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
    private boolean mConnected = false;
    private String status = "disconnected";
    private String mDeviceName;
    private String mDeviceAddress;
    private BluetoothLeService mBluetoothLeService;
    private TextView mReceiveDataTextView = null;
    private TextView mDeviceNameTextView = null;
    private TextView mDeviceAddressTextView = null;
    private TextView mDeviceRssiTextView = null;
    private TextView mDeviceStatusTextView = null;
    private TextView mLockOnTextView = null;
    private TextView mLockOffTextView = null;
    private TextView mInfoTextView = null;
    private TextView mUpgradeTextView = null;
    private TextView mVersionTextView = null;
    private Context mContext = null;
    private boolean isUartThreadRunning = false;
    private Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){

                case 0x00:
                    mDeviceStatusTextView.setText("Connected");
                    break;
                case 0x01:
                    mDeviceStatusTextView.setText("Disconnected");
                    break;
                case 0x02:
                    mInfoTextView.setText(msg.getData().getString("data"));
                    break;
                case 0x03:
                    mInfoTextView.setText(String.valueOf(msg.arg1));
                    break;
                default:
                    break;
            }
        }
    };

    private void registerReceiveDataListener() {
        mBluetoothLeService.setOnDataReceiveListener(new BluetoothLeService.OnCharacteristicListener() {
            @Override
            public void onDataReceive(byte[] buffer, int size) {

                Message message = new Message();
                message.what = 0x02;
                Bundle bundle = new Bundle();
                if (buffer[0] == 0x06){
                    //开锁成功
                    bundle.putString("data","open success!");
                }else if (buffer[0] == 0x07){

                    //关门成功
                    bundle.putString("data","close success!");
                }else{

                    //获取版本号
                    bundle.putString("data",ChangeTool.getInstance().bytetoString(buffer));
                }

                message.setData(bundle);
                mHandler.sendMessage(message);
            }

            @Override
            public void onDeviceConnected(int state) {

                if (state == BluetoothProfile.STATE_CONNECTED){

                    mHandler.sendEmptyMessageDelayed(0x00,10);

                }else{
                    mHandler.sendEmptyMessageDelayed(0x01,10);
                }
            }

            @Override
            public void onDiscoveryService(int status) {

                if (status == BluetoothGatt.GATT_SUCCESS){

                    LogUtil.e(TAG,"onDiscoveryService");
                }
            }
        });

        UpdateCommand.getInstance().setOnReceiveUartUpgradeListener(new UpdateCommand.OnReceiveUartUpgradeListener() {
            @Override
            public void OnReceiveUartUpgradeProcess(int process) {

                Message message = new Message();
                message.what = 0x03;
                message.arg1 = process;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ble_activity);
        mContext = this;
        setStatusBarColor(this.getResources().getColor(R.color.blue));
        mDeviceName = getIntent().getExtras().getString(EXTRAS_DEVICE_NAME);
        mDeviceAddress = getIntent().getExtras().getString(EXTRAS_DEVICE_ADDRESS);
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        initView();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        mBluetoothLeService = null;
    }

    protected void onResume() {
        super.onResume();
        if (mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
            Log.d(TAG, "Connect request result=" + result);
        }

        mDeviceNameTextView.setText(mDeviceName);
        mDeviceAddressTextView.setText(mDeviceAddress);
    }

    private void initView() {

        mDeviceAddressTextView = (TextView)findViewById(R.id.connect_device_address);
        mDeviceNameTextView = (TextView)findViewById(R.id.connect_device_name);
        mDeviceRssiTextView = (TextView)findViewById(R.id.connect_device_rssi);

        mDeviceStatusTextView = (TextView) this.findViewById(R.id.connect_state);

        mDeviceStatusTextView.setText(status);
        mLockOnTextView = (TextView) findViewById(R.id.lock_on_text_view);
        mLockOffTextView = (TextView) findViewById(R.id.lock_off_text_view);
        mInfoTextView  = (TextView) findViewById(R.id.info_text_view);
        mUpgradeTextView = (TextView)findViewById(R.id.upgrade_text_view);
        mVersionTextView = (TextView)findViewById(R.id.reverse_text_view);
        mLockOnTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isUartThreadRunning)
                    return;
                if (mBluetoothLeService != null)
                    UpdateCommand.getInstance().openLockCmd(mBluetoothLeService);
            }
        });

        mLockOffTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isUartThreadRunning)
                    return;
                if (mBluetoothLeService != null)
                    UpdateCommand.getInstance().closeLockCmd(mBluetoothLeService);
            }
        });

        mVersionTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isUartThreadRunning)
                    return;
                if (mBluetoothLeService != null)
                    UpdateCommand.getInstance().uartGetMcuVersion(mBluetoothLeService);
            }
        });

        mUpgradeTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (isUartThreadRunning)
                    return;
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        isUartThreadRunning = true;

                        if (mBluetoothLeService != null) {

                            UpdateCommand.getInstance().uartSendUpgradeCmd(mBluetoothLeService);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            UpdateCommand.getInstance().uartSendFileSize(mContext, mBluetoothLeService);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            UpdateCommand.getInstance().uartSendFile(mContext, mBluetoothLeService);
                            try {
                                Thread.sleep(1500);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            UpdateCommand.getInstance().uartUpgradeCompleted(mBluetoothLeService);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        isUartThreadRunning = false;
                    }
                }).start();
            }
        });
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
                    .getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            mBluetoothLeService.connect(mDeviceAddress);
            registerReceiveDataListener();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };
}
